"""
服务部署规格配置工具模块。
EN: Service deployment specification configuration utility module.

该模块提供了一系列函数，用于获取、管理和处理服务部署相关的资源规格配置，
包括获取特定规格、获取所有规格及其可用性状态、以及获取规格类型等。
EN: This module provides a series of functions for retrieving, managing, and processing service deployment-related
resource specification configurations, including getting specific specifications, getting all specifications
and their availability status, and getting specification types.
"""

# 导入 copy 模块，用于深拷贝对象
# EN: Import the copy module, used for deep copying objects
import copy

# 从 myapp.configs.deploy_service 模块导入 SPECIFICATIONS，该配置定义了服务部署的规格信息
# EN: Import SPECIFICATIONS from myapp.configs.deploy_service module, which defines
# EN: service deployment specification information
from myapp.configs.deploy_service import SPECIFICATIONS


def get_specifications(specifications: str) -> dict:
    """
    根据规格 ID 获取具体的规格配置。
    EN: Retrieves specific specification configurations based on the specification ID.

    Args:
        specifications (str): 规格的唯一标识符。
        EN: specifications (str): The unique identifier for the specification.

    Returns:
        dict: 包含 CPU、内存、GPU 和描述信息的字典。如果未找到，则返回默认配置。
        EN: dict: A dictionary containing CPU, memory, GPU, and description information.
                  If not found, returns a default configuration.
    """
    # 遍历 SPECIFICATIONS 配置中的所有资源类型
    # EN: Iterate through all resource types in the SPECIFICATIONS configuration
    for resource in SPECIFICATIONS.to_dict().values():
        # 检查当前资源类型下是否存在指定的规格 ID
        # EN: Check if the specified specification ID exists under the current resource type
        if resource.get(specifications):
            # 如果找到，返回该规格的配置
            # EN: If found, return the configuration for that specification
            return resource.get(specifications)
    # 如果遍历结束后仍未找到，返回一个默认的规格配置
    # EN: If not found after iterating, return a default specification configuration
    return {'cpu': 4, 'mem': 8000, 'gpu': 0, 'desc': 'ARM: 4 核 8 GB'}


# 返回所有的配置，命中的置为可用，其它置为不可用
# EN: Returns all configurations, marking the matched one as valid and others as invalid
def get_all_specifications(specifications: str) -> list[dict]:
    """
    获取所有可用的规格配置，并标记指定规格的可用性。
    EN: Retrieves all available specification configurations and marks the validity of the specified specification.

    Args:
        specifications (str): 需要标记为可用的规格 ID。
        EN: specifications (str): The specification ID to be marked as valid.

    Returns:
        list[dict]: 包含所有规格配置的列表，每个配置字典中包含 'valid' 字段表示是否可用，
                    以及 'price' 和 'price_desc' 字段。
        EN: list[dict]: A list containing all specification configurations, where each configuration dictionary
                        includes a 'valid' field indicating availability, and 'price' and 'price_desc' fields.
    """
    # 初始化结果列表
    # EN: Initialize the result list
    result = []
    # 遍历 SPECIFICATIONS 配置中的所有资源类型及其下的具体规格
    # EN: Iterate through all resource types and their specific specifications in the SPECIFICATIONS configuration
    for _, v in SPECIFICATIONS.to_dict().items():
        for kk, vv in v.items():
            # 深拷贝当前规格的配置，避免修改原始数据
            # EN: Deep copy the current specification's configuration to avoid modifying original data
            item = copy.deepcopy(vv)
            # 判断当前规格 ID 是否与传入的 specifications 匹配
            # EN: Check if the current specification ID matches the provided specifications
            if kk == specifications:
                # 如果匹配，标记为可用
                # EN: If matched, mark as valid
                item['valid'] = True
            else:
                # 如果不匹配，标记为不可用
                # EN: If not matched, mark as invalid
                item['valid'] = False
            # 添加规格 ID
            # EN: Add specification ID
            item['specifications'] = kk
            # 获取价格，如果不存在则默认为 0
            # EN: Get price, default to 0 if not present
            price = vv.get('price', 0)
            # 计算并设置价格（单位：元/分钟）
            # EN: Calculate and set price (unit: RMB/minute)
            item['price'] = price / 10000
            # 设置价格描述
            # EN: Set price description
            item['price_desc'] = f'{price / 10000}元/分钟'
            # 将处理后的规格添加到结果列表
            # EN: Add the processed specification to the result list
            result.append(item)
    # 返回所有规格配置列表
    # EN: Return the list of all specification configurations
    return result


def get_specifications_type(spec: str) -> str or None:
    """
    根据规格 ID 获取其所属的规格类型（例如 'CPU', 'GPU'）。
    EN: Retrieves the type of a specification (e.g., 'CPU', 'GPU') based on its ID.

    Args:
        spec (str): 规格的唯一标识符。
        EN: spec (str): The unique identifier for the specification.

    Returns:
        str or None: 规格类型字符串，如果未找到则返回 None。
        EN: str or None: The specification type string, or None if not found.
    """
    # 遍历 SPECIFICATIONS 配置中的所有资源类型及其下的具体规格
    # EN: Iterate through all resource types and their specific specifications in the SPECIFICATIONS configuration
    for k, v in SPECIFICATIONS.to_dict().items():
        for kk, _ in v.items():
            # 如果找到匹配的规格 ID
            # EN: If a matching specification ID is found
            if kk == spec:
                # 返回该规格所属的类型
                # EN: Return the type to which this specification belongs
                return k

    # 如果遍历结束后仍未找到，返回 None
    # EN: If not found after iterating, return None
    return None
